//
//  ControlViewController.m
//  upnpxdemo
//
//  Created by a  on 13-8-26.
//  Copyright (c) 2013年 wiimu.inc. All rights reserved.
//

#import "ControlViewController.h"
#import "NYSliderPopover.h"
#import <QuartzCore/QuartzCore.h>
#import "CustomAlertView.h"
#import "MMProgressHUD.h"

enum playButtonState
{
    playButton_play,
    playButton_pause
};

enum muteButtonState
{
    muteButton_mute,
    muteButton_nmute
};

#define REFRESHMINTIME 2

@interface ControlViewController ()
<serviceSetNewDownUriDelegate,serviceGetPlayerStatusDelegate,servicePlayControlDelegate,serviceChangeVolumeDelegate,servicePlaySeekDelegate,serviceVolumeMuteDelegate,serviceSetDownCmdDelegate>
{
    float volume;
    NSTimer * timer;
    
    int playButtonState;
    int muteButtonState;
    float lastVolumeBeforeMute;
    
    long long m_totlen;
    
    int rightBandShowTime;//用于右侧条刷新，5s消失
    
    int volumeRefreshTime;//用于音量条拖动更新显示，如果遇到调整音量，则两次之内不会接受refresh
    int seekRefreshTime;//同上面
    
    BOOL isLoadingFirstTime;//是否为开始载入，是则loading，否则不添加loading
    
    BOOL isRightAnimation;//右侧渐隐动画是否进行
}

@property (nonatomic, strong) IBOutlet UILabel * playTimeLabel;
@property (nonatomic, strong) IBOutlet UIButton *muteButton;
@property (nonatomic, strong) IBOutlet UIButton *stopButton;
@property (nonatomic, strong) IBOutlet NYSliderPopover *playSlider;
@property (nonatomic, strong) IBOutlet NYSliderPopover *volumeSlider;
@property (nonatomic, strong) IBOutlet UIButton *playButton;
@property (nonatomic, strong) IBOutlet UIButton *downloadButton;
@property (nonatomic, strong) IBOutlet UIImageView *modeIcon;
@property (nonatomic, strong) IBOutlet UILabel * musicTitle;

@property (strong) IBOutlet UIView * controlView;
@property (strong) IBOutlet UIView * rightBandView;

- (IBAction)sliderValueChanged:(id)sender;
@end

@implementation ControlViewController
@synthesize playStatusDic;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //启动http服务器
    if([[GlobalService sharedInstance] checkIfIPChanged])
    {
        [[GlobalService sharedInstance] stopHTTPServer];
        [[GlobalService sharedInstance] startHTTPServer];
    }
    
    rightBandShowTime = 0;
    
    volumeRefreshTime = REFRESHMINTIME+1;
    seekRefreshTime = REFRESHMINTIME+1;
    
    isLoadingFirstTime = YES;
    
    isRightAnimation = NO;
    
    [self prepareUI];
    
    timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
    
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

-(void)viewDidAppear:(BOOL)animated
{
    _rightBandView.center = CGPointMake(_rightBandView.center.x, _controlView.center.y);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - navigation methods
-(NSString *)navigationBarTitle
{
    return [[GlobalInfo sharedInstance].currentSelectedUpnPInfo objectForKey:@"ssid"];
}

-(BOOL)isNewVersionButtonEnabled
{
    return YES;
}

-(IBAction)backButtonPressed:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"PopTabBarController" object:self];
}

#pragma mark -
#pragma mark IBAction
//button methods
-(IBAction)stopButtonPressed:(id)sender
{
    [[GlobalService sharedInstance] playControl:self withCommand:@"stop"];
}

-(IBAction)playButtonPressed:(id)sender
{
    if(playButtonState == playButton_play)
    {
        [[GlobalService sharedInstance] playControl:self withCommand:@"play"];
    }
    else
    {
        [[GlobalService sharedInstance] playControl:self withCommand:@"pause"];
    }
}

-(IBAction)increaseButtonPressed:(id)sender
{
    [self changeVolume:self.volumeSlider.value+0.1];
}

-(IBAction)decreaseButtonPressed:(id)sender
{
    [self changeVolume:self.volumeSlider.value-0.1];
}

-(IBAction)muteButtonPressed:(id)sender
{
    if(muteButtonState == muteButton_mute)
    {
        [[GlobalService sharedInstance] setVolumeMute:self isMute:YES];
    }
    else
    {
        [[GlobalService sharedInstance] setVolumeMute:self isMute:NO];
    }
}

//volumeSlider
- (IBAction)sliderValueChanged:(id)sender
{
    NYSliderPopover * slider = (NYSliderPopover *)sender;
    
    slider.popover.textLabel.text = [NSString stringWithFormat:@"%.2f", slider.value];
}

-(IBAction)touchUpInSlider:(id)sender
{
    if(sender == _volumeSlider)
    {
        [self changeVolume:_volumeSlider.value];
    }
    else if(sender == _playSlider)
    {
        self.playTimeLabel.text = [self caculateTimeText:m_totlen*self.playSlider.value/1000 andTotal:m_totlen/1000];
        
        seekRefreshTime = 0;
        
        [[GlobalService sharedInstance] playSeek:self seekTo:[NSString stringWithFormat:@"%lld",(long long)(m_totlen*_playSlider.value/1000)]];
    }
}

-(IBAction)downloadButtonPressed:(id)sender
{
    [[GlobalService sharedInstance] setNewDownUri:self uri:[GlobalInfo sharedInstance].currentPlayInfo[@"iuri"]];
    [[GlobalService sharedInstance] setDownloadCmd:self cmd:@"start"];
}

#pragma mark -
#pragma mark private methods
-(void)prepareUI
{
    [self refreshUIStatus:self.playStatusDic];
    
    self.playStatusDic = nil;
    
    [_playSlider setThumbImage:[UIImage imageNamed:@"sliderbutton_normal.png"] forState:UIControlStateNormal];
    [_playSlider setThumbImage:[UIImage imageNamed:@"sliderbutton_press.png"] forState:UIControlStateHighlighted];
    [_playSlider setMinimumTrackImage:[UIImage imageNamed:@"hslider_min.png"] forState:UIControlStateNormal];
    [_playSlider setMaximumTrackImage:[UIImage imageNamed:@"hslider_max.png"] forState:UIControlStateNormal];
    
    [_volumeSlider setThumbImage:[UIImage imageNamed:@"sliderbutton_normal.png"] forState:UIControlStateNormal];
    [_volumeSlider setThumbImage:[UIImage imageNamed:@"sliderbutton_press.png"] forState:UIControlStateHighlighted];
    [_volumeSlider setMinimumTrackImage:[UIImage imageNamed:@"hslider_min.png"] forState:UIControlStateNormal];
    [_volumeSlider setMaximumTrackImage:[UIImage imageNamed:@"hslider_max.png"] forState:UIControlStateNormal];
    
    _volumeSlider.transform = CGAffineTransformMakeRotation(-1.57079633);
}

- (NSString *)tabImageName
{
	return @"TAB_ICON_2.png";
}

- (NSString *)tabTitle
{
	return NSLocalizedString(@"PLAYCONTROL",@"");
}

-(void)getPlayerStatus
{
    [[GlobalService sharedInstance] getPlayerStatus:self];
}

-(void)timerMethod
{
    [self getPlayerStatus];

    if(_rightBandView.alpha == 1)
    {
        rightBandShowTime++;
        if(rightBandShowTime > 5)
        {
            [self rightBandHideAnimation];
        }
    }
}

-(void)changeVolume:(float)toVolume
{
    volumeRefreshTime = 0;
    
    if(toVolume > 1) toVolume = 1;
    if(toVolume < 0) toVolume = 0;
    
    self.volumeSlider.value = toVolume;
    
    [self rightBandShowAnimation];
    
    [[GlobalService sharedInstance] changeVolume:self withVol:toVolume];
}

-(void)refreshUIStatus:(NSDictionary *)statusDic
{
    if(statusDic == nil || [statusDic objectForKey:@"status"] == nil)
    {
        return;
    }
    
    //playstatus
    NSString * playStatus = [statusDic objectForKey:@"status"];
    
    //title
    if([playStatus isEqualToString:@"play"])
    {
        if([statusDic[@"Title"] length] != 0)
        {
            _musicTitle.text = statusDic[@"Title"];
        }
        else
        {
            NSArray * arr = [statusDic[@"iuri"] componentsSeparatedByString:@"/"];
            if([[arr lastObject] length] != 0)
            {
                _musicTitle.text = [arr lastObject];
            }
            else
            {
                _musicTitle.text = statusDic[@"iuri"];
            }
        }
    }
    else
    {
        _musicTitle.text = @"";
    }
    
    if([playStatus isEqualToString:@"none"])
    {
        if(isLoadingFirstTime == NO)
        {
            [MMProgressHUD dismiss];
            isLoadingFirstTime = YES;
        }
        
        _stopButton.enabled = NO;
        _playButton.enabled = NO;
        _playSlider.enabled = NO;
        _downloadButton.enabled = NO;
        _modeIcon.hidden = YES;
        
        [_playButton setBackgroundImage:[UIImage imageNamed:@"playbutton_normal.png"] forState:UIControlStateNormal];
        [_playButton setBackgroundImage:[UIImage imageNamed:@"pausebutton_press.png"] forState:UIControlStateSelected];
        playButtonState = playButton_play;
    }
    else if([playStatus isEqualToString:@"stop"])
    {
        if(isLoadingFirstTime == NO)
        {
            [MMProgressHUD dismiss];
            isLoadingFirstTime = YES;
        }
        
        _stopButton.enabled = NO;
        _playButton.enabled = YES;
        _playSlider.enabled = NO;
        _downloadButton.enabled = NO;
        _modeIcon.hidden = YES;
        
        [_playButton setBackgroundImage:[UIImage imageNamed:@"playbutton_normal.png"] forState:UIControlStateNormal];
        [_playButton setBackgroundImage:[UIImage imageNamed:@"pausebutton_press.png"] forState:UIControlStateSelected];
        playButtonState = playButton_play;
    }
    else if([playStatus isEqualToString:@"load"])
    {
        _stopButton.enabled = NO;
        _playButton.enabled = NO;
        _playSlider.enabled = NO;
        _downloadButton.enabled = NO;
        _modeIcon.hidden = YES;
        
        if(isLoadingFirstTime == YES)
        {
            [MMProgressHUD showWithStatus:@"loading..."];
            isLoadingFirstTime = NO;
        }
        
        [_playButton setBackgroundImage:[UIImage imageNamed:@"playbutton_normal.png"] forState:UIControlStateNormal];
        [_playButton setBackgroundImage:[UIImage imageNamed:@"pausebutton_press.png"] forState:UIControlStateSelected];
        playButtonState = playButton_play;
    }
    else
    {
        if(isLoadingFirstTime == NO)
        {
            [MMProgressHUD dismiss];
            isLoadingFirstTime = YES;
        }
        
        _stopButton.enabled = YES;
        _playButton.enabled = YES;
        _playSlider.enabled = YES;
        _downloadButton.enabled = YES;
        _modeIcon.hidden = NO;

        if([playStatus isEqualToString:@"play"])
        {
            [_playButton setBackgroundImage:[UIImage imageNamed:@"pausebutton_normal.png"] forState:UIControlStateNormal];
            [_playButton setBackgroundImage:[UIImage imageNamed:@"pausebutton_press.png"] forState:UIControlStateSelected];
            playButtonState = playButton_pause;
        }
        else if([playStatus isEqualToString:@"pause"])
        {
            [_playButton setBackgroundImage:[UIImage imageNamed:@"playbutton_normal.png"] forState:UIControlStateNormal];
            [_playButton setBackgroundImage:[UIImage imageNamed:@"pausebutton_press.png"] forState:UIControlStateSelected];
            playButtonState = playButton_play;
        }
        else
        {
            NSLog(@"playStatus %@",playStatus);
        }
    }
    
    //mode
    NSString * mode = [statusDic objectForKey:@"mode"];
    if([mode intValue] == PLAYER_MODE_AIRPLAY)
    {
        _playButton.enabled = NO;
        _playSlider.enabled = NO;
        _modeIcon.image = [UIImage imageNamed:@"airplay"];
    }
    
    if([mode intValue] == PLAYER_MODE_DLNA)
    {
        _modeIcon.image = [UIImage imageNamed:@"dlna"];
    }
    else
    {
//        _downloadButton.enabled = NO;
    }
    
    //mute
    NSString * mute = [statusDic objectForKey:@"mute"];
    if([mute intValue] == 1)
    {
        [_muteButton setImage:[UIImage imageNamed:@"increasebutton_normal.png"] forState:UIControlStateNormal];
        
        muteButtonState = muteButton_nmute;
    }
    else
    {
        [_muteButton setImage:[UIImage imageNamed:@"mutebutton_normal.png"] forState:UIControlStateNormal];
        
        muteButtonState = muteButton_mute;
    }
    
    if(volumeRefreshTime++ > REFRESHMINTIME)
    {
        volumeRefreshTime = REFRESHMINTIME+1;
        
        //vol
        NSString * vol = [statusDic objectForKey:@"vol"];
        self.volumeSlider.value = volume = (float)[vol intValue]/100;
    }
    
    if(seekRefreshTime++ > REFRESHMINTIME)
    {
        seekRefreshTime = REFRESHMINTIME+1;
        
        //curpos
        NSString * curpos = [statusDic objectForKey:@"curpos"];
        NSString * totlen = [statusDic objectForKey:@"totlen"];
        m_totlen = [totlen longLongValue];

        self.playTimeLabel.text = [self caculateTimeText:[curpos floatValue]/1000 andTotal:[totlen floatValue]/1000];

        self.playSlider.value = (float)[curpos floatValue]/([totlen floatValue]+1);
    }
}

-(void)stopAllTimers
{
    if(timer != nil && [timer isValid])
    {
        [timer invalidate];
        timer = nil;
    }
}

-(NSString *)caculateTimeText:(long long)curNum andTotal:(long long)totNum
{
    int curH = (int)(curNum/3600);
    int curM = (int)(curNum/60);
    curM = curM%60;
    int curS = curNum%60;
    
    int totH = (int)(totNum/3600);
    int totM = (int)(totNum/60);
    totM = totM%60;
    int totS = totNum%60;
    
    return [NSString stringWithFormat:@"%@%d:%@%d:%@%d / %@%d:%@%d:%@%d",curH>9?@"":@"0",curH,curM>9?@"":@"0",curM,curS>9?@"":@"0",curS,totH>9?@"":@"0",totH,totM>9?@"":@"0",totM,totS>9?@"":@"0",totS];
}

#pragma mark -
#pragma mark top animations
-(void)topAnimationMethods
{

}

#pragma mark -
#pragma mark right animations
-(void)rightBandShowAnimation
{
    rightBandShowTime = 0;
    
    if(isRightAnimation == YES || _rightBandView.alpha == 1)
    {
        return;
    }
    
    isRightAnimation = YES;
    
    CABasicAnimation *fadein = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadein.fromValue = [NSNumber numberWithFloat:0];
    fadein.toValue = [NSNumber numberWithFloat:1];
    fadein.duration = 0.4;
    fadein.fillMode = kCAFillModeForwards;
    fadein.removedOnCompletion = NO;
    fadein.delegate = self;
    [_rightBandView.layer addAnimation:fadein forKey:@"rightIn"];
}

-(void)rightBandHideAnimation
{
    rightBandShowTime = 0;
    
    if(_rightBandView.alpha == 0)
    {
        return;
    }
    
    CABasicAnimation *fadeout = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeout.fromValue = [NSNumber numberWithFloat:1];
    fadeout.toValue = [NSNumber numberWithFloat:0];
    fadeout.duration = 0.4;
    fadeout.fillMode = kCAFillModeForwards;
    fadeout.removedOnCompletion = NO;
    fadeout.delegate = self;
    [_rightBandView.layer addAnimation:fadeout forKey:@"rightOut"];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    if(flag)
    {
        if(anim == [_rightBandView.layer animationForKey:@"rightIn"])
        {
            isRightAnimation = NO;
            _rightBandView.alpha = 1;
            
        }
        else if(anim == [_rightBandView.layer animationForKey:@"rightOut"])
        {
            isRightAnimation = NO;
            _rightBandView.alpha = 0;
        }
    }
}

#pragma mark -
#pragma mark servicecallbacks
-(void)serviceGetPlayerStatusCallBack:(NSDictionary*)dicCallBack
{
    NSDictionary * dic = dicCallBack;
    
    if(dic == nil || [[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_FAIL intValue])
    {
        
        
        return;
    }
    else if([[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_CONNECTIONFAIL intValue] || [[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_TIMEOUT intValue])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PopTabBarController" object:self];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ErrorComeBack" object:nil];
    }
    
    if([[GlobalService sharedInstance] checkIfIPChanged])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PopTabBarController" object:self];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ErrorComeBack" object:nil];
    }
    
    [GlobalInfo sharedInstance].currentPlayInfo = dic;

    [self refreshUIStatus:dic];
}

-(void)servicePlayControlCallBack:(NSDictionary*)dicCallBack
{
    
}

-(void)serviceChangeVolumeCallBack:(NSDictionary*)dicCallBack
{

}

-(void)servicePlaySeekCallBack:(NSDictionary*)dicCallBack
{

}

-(void)serviceVolumeMuteCallBack:(NSDictionary*)dicCallBack
{}

-(void)serviceSetNewDownUriCallBack:(NSDictionary*)dicCallBack
{
    if(dicCallBack == nil || [[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_FAIL intValue])
    {
        
        
        return;
    }
    else if([[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_CONNECTIONFAIL intValue] || [[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_TIMEOUT intValue])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PopTabBarController" object:self];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ErrorComeBack" object:nil];
    }
    
    NSString * infoStr = nil;
    
    if([dicCallBack[@"info"] isEqualToString:@"OK"])
    {
        infoStr = NSLocalizedString(@"MUSICDOWN_DOWNBEGIN", @"");
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ADDNEWMUSICDOWN" object:nil];
    }
    else if([dicCallBack[@"info"] isEqualToString:@"Already in todown"])
    {
        infoStr = NSLocalizedString(@"MUSICDOWN_ISDOWNLOADING", @"");
    }
    else if([dicCallBack[@"info"] isEqualToString:@"Already in finished"])
    {
        infoStr = NSLocalizedString(@"MUSICDOWN_DOWNLOADED", @"");
    }
    else if([dicCallBack[@"info"] isEqualToString:@"USB not ready"])
    {
        infoStr = NSLocalizedString(@"MUSICDOWN_NEEDUSB", @"");
    }
    else
    {
        infoStr = dicCallBack[@"info"];
    }
    
    [self.view makeToast:infoStr
                duration:3.0
                position:@"bottom"
                   title:NSLocalizedString(@"ALERT_TITLE",@"")];
}

-(void)serviceSetDownCmdCallBack:(NSDictionary*)dicCallBack{}
@end
